package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    //进入controller之前进行身份验证
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session中获取当前用户信息
        Employee employee = (Employee) request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);

        if (employee != null) {
            //如果能够获取到，证明身份合法
            //将用户信息保存到ThreadLocal
            EmployeeHolder.set(employee);

            //放行
            return true;
        }else {
            //如果获取不到，返回错误提示
            log.info("用户身份不合法");

            //返回错误信息，前端拿到这个信息之后，就应该跳转到登录页面
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            String json = new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);

            return false;
        }

    }

    //当请求离开服务器的时候，移除掉ThreadLocal中的对象
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remover();
    }
}
